﻿Public Class ANSI_C_Math

    ''' <summary>
    ''' Returns the resulting floating point value from multiplying x (the significand) by 2 raised to the power of exp (the exponent).
    ''' </summary>
    ''' <param name="x">Floating point value representing the significand.</param>
    ''' <param name="exp">Value of the exponent.</param>
    ''' <returns>The function returns: x * 2^exp</returns>
    Public Shared Function ldexp(ByVal x As Double, ByVal exp As Integer) As Double
        Return x * 2 ^ exp
    End Function

    ''' <summary>
    ''' Breaks the floating point number x into its binary significand (a floating point value between 0.5(included) and 1.0(excluded)) and an integral exponent for 2, such that:
    ''' x = significand * 2 exponent
    ''' The exponent is stored in the location pointed by exp, and the significand is the value returned by the function.
    ''' If x is zero, both parts (significand and exponent) are zero.
    ''' </summary>
    ''' <param name="x">Floating point value to be computed.</param>
    ''' <param name="exp">Pointer to an int object where the value of the exponent is to be stored.</param>
    ''' <returns>The binary significand of x.
    ''' This value is the floating point value in the interval [0.5,1) which, once multiplied by 2 raised to the power of exp, yields x.</returns>
    Public Shared Function frexp(ByVal x As Double, ByRef exp As Integer) As Double
        If x = 0 Then
            exp = 0
            Return 0
        Else

            Dim tmpExp As Integer = tmpExp = Math.Round(Math.Log(x, 2), 0, MidpointRounding.AwayFromZero)

            Dim mantissa As Double = x / (2 ^ tmpExp)
            If mantissa >= 1 Then
                exp = tmpExp + 1
                Return mantissa / 2
            Else
                exp = tmpExp
                Return mantissa
            End If
        End If
    End Function
End Class
